/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.action.retrieve;

import com.inspur.edp.bef.api.be.IBEContext;
import com.inspur.edp.bef.core.lock.LockService;
import com.inspur.edp.bef.core.scope.SingleBETypeExtension;
import com.inspur.edp.cef.api.scope.ICefScopeNodeParameter;
import java.util.stream.Collectors;

public class AddLockExtension extends SingleBETypeExtension {

   //region Constructor

   public AddLockExtension() {
      super();
   }

   //endregion

   @Override
   public void onExtendSetComplete() {
      if (getParameters().size() == 0) {
         return;
      }

      //① 批量加锁；
      multiAddLock();
      //② 执行回调函数；
      executeAction();
   }

   /**
    * 调用回调函数
    */
   private void executeAction() {
      //无论是否加锁成功，一定调用回调函数，返回lockId,未加锁成功则赋值null
      for (ICefScopeNodeParameter item : getParameters()) {
         AddLockScopeNodeParameter par = (AddLockScopeNodeParameter) item;
         par.executeAction(par.getBEContext());
      }
   }

   /**
    * 批量加锁
    */
   private void multiAddLock() {
      if((getParameters()==null||getParameters().size()==0))
         return;
      IBEContext context =((AddLockScopeNodeParameter)getParameters().get(0)).getBEContext();
      LockService.getInstance().addLocks(getCurrentBeType(), getParameters().stream()
          .map(item -> ((AddLockScopeNodeParameter) item).getBEContext().getID()).collect(
              Collectors.toList()));
   }
}
